var graph = new joint.dia.Graph;
//自定义link
joint.shapes.standard.Link.define('app.Link', {
    router: {
        name: 'normal'
    },
    labels: [],
    attrs: {
        line: {
            stroke: '#20C1DD',
            strokeDasharray: '0',
            strokeWidth: 2,
            fill: 'none',
            sourceMarker: {
                type: 'path',
                d: 'M 0 0 0 0',
                stroke: 'none'
            },
            targetMarker: {
                type: 'path',
                d: 'M 0 -5 -10 0 0 5 z',
                stroke: 'none'
            }
        }
    }
}, {

    getMarkerWidth: function(type) {
        var d = (type === 'source') ? this.attr('line/sourceMarker/d') : this.attr('line/targetMarker/d');
        return this.getDataWidth(d);
    },

    getDataWidth: _.memoize(function(d) {
        return (new g.Path(d)).bbox().width;
    })

}, {

    connectionPoint: function(line, view, magnet, opt, type, linkView) {
        var markerWidth = linkView.model.getMarkerWidth(type);
        opt = { offset: markerWidth, stroke: true };
        // connection point for UML shapes lies on the root group containg all the shapes components
        if (view.model.get('type').indexOf('uml') === 0) opt.selector = 'root';
        return joint.connectionPoints.boundary.call(this, line, view, magnet, opt, type, linkView);
    }
});

var paper = new joint.dia.Paper({
    width: 2000,
    height: 1500,
    model: graph,
    gridSize: 10,
    snapLinks: true,
    linkPinning: false,
    defaultLink: new joint.dia.Link({
        // router: { name: 'manhattan' },
    //    connector: { name: 'rounded' },
        smooth: true,
        attrs: {
            '.connection': {
                stroke: '#20C1DD',
                'stroke-width': 2,
              //  'stroke-dasharray': '5 2',
                pointerEvents: 'none',
            },
            '.marker-target': {
                fill: '#20C1DD',
                stroke: '#fff',
                d: 'M 10 0 L 0 5 L 10 10 z'
            }
        },
    }),
    defaultConnectionPoint: joint.shapes.app.Link.connectionPoint

});
//paper背景
var bgimage = '';
paper.drawBackground({
    image : bgimage
});

//控制纸张
var paperScroller = new joint.ui.PaperScroller({
    paper: paper,
    autoResizePaper: true,
    padding: 50,
    cursor: 'grab'
});
// 移动纸张
paper.on('blank:pointerdown', paperScroller.startPanning);
$('#paper').append(paperScroller.render().el);
paperScroller.center();    //移动到页面的中间


var commandManager = new joint.dia.CommandManager({
    graph: graph
});

//提示实例
new joint.ui.Tooltip({
    rootTarget: document.body,
    target: '[data-tooltip]',
    padding: 15
});


//元素间的对齐线
/*var snaplines = new joint.ui.Snaplines({ paper: paper });
snaplines.startListening();*/


//鹰眼开始
var nav = new joint.ui.Navigator({
    paperScroller: paperScroller,
    width: 133,
    height: 100,
    padding: 5,
    model: graph,
    gridSize: 1,
//        zoomOptions: { max: 2, min: 0.12 }
});
nav.$el.appendTo('#myholder-small');
nav.render();
//小图结束


//tooltip模块
new joint.ui.Tooltip({
    target: '[data-tooltip]',
    rootTarget: document.body,
    direction: 'auto',
    padding: 15,
});

//显示父页面的工具条
$('.form-timeline', window.parent.document).animate({opacity:1},'swing');

var tableBgArr = ['#4c87b9','#2F4554','#91C7AE','#D48265','#61A0A8','#C23531'];
var colorNum = -1;
//请求表数据
requestTable('6fdea81f-3f32-4a0f-afc2-755903cc4be6',null,{isRightOpen:'',isLeftOpen:''},function () {
    paperScroller.centerContent();
    var model = graph.getElements()[0];
    var ele =paper.findViewByModel(model);
    ele.highlight(null, {
        highlighter: {
            name: 'stroke',
            options: {
                padding: 6,
                rx: 3,
                ry: 3,
                attrs: {
                    'stroke-width': 3,
                    stroke: '#D05454'
                }
            }
        }
    });
});


//单击元素时的函数
paper.on('cell:pointerclick',function(cellView){
 //   console.log(cellView.model);
    if(cellView.model.attributes.type === 'basic.TextBlock') {
        var  halo = new joint.ui.Halo({ cellView: cellView});
        //元素只连接元素
        halo.on('action:link:add', function(link) {
            if (!link.get('source').id || !link.get('target').id) {
                link.remove();
            }
        });
        halo.render();
        halo.removeHandles();

        if(cellView.model.attributes.attrs.isRightOpen) {       //判断是否展开，右边icon状态
            halo.addHandle({ name: 'myaction', position: 'ne', icon: 'img/wancheng.svg' });
        }else {
            halo.addHandle({ name: 'myaction', position: 'ne', icon: 'img/zhankai.svg' });
        }

        if(cellView.model.attributes.attrs.isLeftOpen) {       //判断是否展开，右边icon状态
            halo.addHandle({ name: 'myactionleft', position: 'nw', icon: 'img/wancheng.svg' });
        }else {
            halo.addHandle({ name: 'myactionleft', position: 'nw', icon: 'img/zhankai.svg' });
        }

     //   halo.addHandle({ name: 'myactionleft', position: 'nw', icon: 'img/zhankai.svg' });
        //halo插件的tooltip
        halo.changeHandle('myaction', {
            attrs: {
                '.handle': {
                    'data-tooltip-class-name': 'small',
                    'data-tooltip': '影响',
                    'data-tooltip-position': 'left'
                }
            }
        });
        halo.changeHandle('myactionleft', {
            attrs: {
                '.handle': {
                    'data-tooltip-class-name': 'small',
                    'data-tooltip': '溯源',
                    'data-tooltip-position': 'right'
                }
            }
        });
        //点击自定义图标
       /* halo.on('action:myaction:pointerdown', function(evt) {
            evt.stopPropagation();
            //判断是否向右加载
            if(cellView.model.attributes.attrs.isRightLoad){ //已经加载过（此时加载）
                    //判断是否展开
                var   currentElement = cellView.model; //当前元素
                recursion(currentElement,{outbound:true},cellView.model.attributes.attrs.isRightOpen); //加载影响的所有元素

                console.log(cellView.model.attributes.attrs.isRightOpen);
                if(cellView.model.attributes.attrs.isRightOpen) { //已经展开
                        cellView.model.attributes.attrs.isRightOpen = false;
                        halo.changeHandle('myaction', { icon: 'img/zhankai.svg' });

                    }else {   //未展开时
                        cellView.model.attributes.attrs.isRightOpen = true;
                        halo.changeHandle('myaction', { icon: 'img/shousuo.svg' });
                    }

            }else {                                     //没有加载过（此时加载）
                requestTable(cellView.model.id,'after',{isRightOpen:true,isRightLoad:true});
                showTable(cellView.model,{outbound:true},'right');
                
                cellView.model.attributes.attrs.isRightLoad = true;
                cellView.model.attributes.attrs.isRightOpen = true;
                halo.changeHandle('myaction', { icon: 'img/shousuo.svg' });
            }

        });
        halo.on('action:myactionleft:pointerdown', function(evt) {
            evt.stopPropagation();

            //判断是否向左加载
            if(cellView.model.attributes.attrs.isLeftLoad) { //已经加载过（此时加载）


                var   currentElement = cellView.model; //当前元素
                recursion(currentElement,{inbound:true},cellView.model.attributes.attrs.isLeftOpen);
                //判断是否展开
                if(cellView.model.attributes.attrs.isLeftOpen) { //已经展开
                    cellView.model.attributes.attrs.isLeftOpen = false;
                    halo.changeHandle('myactionleft', { icon: 'img/zhankai.svg' });
                }else {//未展开时
                    cellView.model.attributes.attrs.isLeftOpen = true;
                    halo.changeHandle('myactionleft', { icon: 'img/shousuo.svg' });
                }

            }else {                      //没有加载过（此时加载）
                requestTable(cellView.model.id,'before',{isRightOpen:'',isLeftOpen:true,isRightLoad:'',isLeftLoad:true});
                showTable(cellView.model,{inbound:true},'left');
                cellView.model.attributes.attrs.isLeftLoad = true;
                cellView.model.attributes.attrs.isLeftOpen = true;
                halo.changeHandle('myactionleft', { icon: 'img/shousuo.svg' });
            }
        });*/
        halo.on('action:myaction:pointerdown', function(evt) {
            evt.stopPropagation();
            //判断是否向右展开
            if(!cellView.model.attributes.attrs.isRightOpen){    //如果没有展开

                cellView.model.attributes.attrs.isRightOpen = true;
                requestTable(cellView.model.id,'after',{isRightOpen:true});
                halo.changeHandle('myaction', { icon: 'img/wancheng.svg' });
                showTable(cellView.model,{outbound:true},'right');
            }
        });
        halo.on('action:myactionleft:pointerdown', function(evt) {
            evt.stopPropagation();
            //判断是否向左展开
            if(!cellView.model.attributes.attrs.isLeftOpen){    //如果没有展开

                cellView.model.attributes.attrs.isLeftOpen = true;
                requestTable(cellView.model.id,'before',{isLeftOpen:true});
                halo.changeHandle('myactionleft', { icon: 'img/wancheng.svg' });
                showTable(cellView.model,{inbound:true},'left');
            }
        });

    }

});


//右键点击元素
paper.on('cell:contextmenu',function(cellView,evt,x,y){

    if(cellView.model.attributes.type === "basic.TextBlock"){
        var fa_item_ul = $('<ul class="vakata-context jstree-contextmenu jstree-default-contextmenu item_ul"></ul>');
        var  fa_item_li = ['打开','浏览数据','SQL','创建交换流程（以本对象为输入）','创建交换流程（以本对象为输出'];  //一级的li
        var e = evt || window.evt;

        $.each(fa_item_li,function (i, v) {
            fa_item_ul.append('<li class=""><a class="" href="#">'+v+'</a></li>')
        });

        fa_item_ul.appendTo($('#app'));
        $('.item_ul').css({'display':'block','position':'absolute','z-index':'1000','background':'#fff','left':''+(e.clientX+10)+'px','top':''+(e.clientY+10)+'px'});
    }


});
//右键删除列表
paper.on('blank:contextmenu',function(){
    $('.item_ul').remove();
    console.log(graph.getLinks());
});

//点击doucment删除列表
$(document).click(function(e){
    var tar = $(e.target);
    if(!tar.hasClass('erFisrtMenu')){
        $('.item_ul').remove()
    }
});

//递归函数
function recursion(currentElement,obj,isOpen) {
    var list = [],  //元素id数组
        lineList=[];  //线id数组
        //    flag=true,    //流程控制
    list.push(currentElement.id); //排除当前元素
    findRelateModel(currentElement);
    console.log(list);
    function findRelateModel(currentElement){     //子元素相关的所有元素
        /*    if (flag){
                var NeighborsBPMNArr = graph.getNeighbors(currentElement,{inbound:true});  //相邻元素数组
                flag = false;
            }else {
                NeighborsBPMNArr = graph.getNeighbors(currentElement);
            }*/
        var NeighborsBPMNArr = graph.getNeighbors(currentElement,obj);  //相邻元素数组
        $.each(NeighborsBPMNArr,function(i,v){        //遍历相关元素
            if(list.indexOf(v.id) === -1){
                list.push(v.id);
                if(isOpen){
                    paper.findViewByModel(v).$el.hide(300)
                }else {
                    paper.findViewByModel(v).$el.show(300)
                }
           //     paper.findViewByModel(v).$el.toggle(300);
                var NeighborsLinkArr = graph.getConnectedLinks(v); //元素相关线的数组
                $.each(NeighborsLinkArr,function(i,v){       //遍历相关线
                    console.log(v);
                    if (lineList.indexOf(v.id) === -1){
                        lineList.push(v.id);
                        if(isOpen){
                            paper.findViewByModel(v).$el.hide(300)
                        }else {
                            paper.findViewByModel(v).$el.show(300);

                        }

                    }
                });
                findRelateModel(v);               //回调
            }
        })
    }
}




//请求表和流程数据封装
function requestTable(objectId,forward,isOpen,cb) {
    $.ajax({
            url : requestUrl +'/rest/dataRelation/dataRelation',
            type : 'GET',
            dataType : 'JSON',
            data:{"objectId":objectId,"forward":forward},
            success: function (result) {

                //去除元素上多余的线
                var linklikeArr=[];
               $.each(result.object.lines,function (i, v) {
                   var topThis = v;
                   if(graph.getLinks().length > 0){
                       $.each(graph.getLinks(),function (i, v) {
                           if(v.attributes.source.id === topThis.from && v.attributes.target.id === topThis.to){
                               if(linklikeArr.indexOf(topThis) === -1 ){
                                   linklikeArr.push(topThis)
                               }
                           }
                       });
                   }
               });
                var  linkArr = array_diff(result.object.lines, linklikeArr);

                var elementlikeArr = [];
                $.each(result.object.vertexs,function (i, v) {
                    var topThis = v;
                    if(graph.getElements().length > 0){
                        $.each(graph.getElements(),function (i, v) {
                            if(v.attributes.id === topThis.vertexId){
                             if(elementlikeArr.indexOf(topThis) === -1 ){
                                 elementlikeArr.push(topThis)
                             }
                            }
                        });
                    }
                });
             var  elementArr = array_diff(result.object.vertexs, elementlikeArr);

                //初始化元素
                var tableObjArr = [];
                $.each(elementArr,function (i, v) {
                    if(v.vertexType === 'dataobj' || v.vertexType === 'sql'){
                        if(colorNum === 5){
                            colorNum = 0
                        }else {
                            colorNum+=1;
                        }

                        console.log(colorNum);
                        var tableObj = new joint.shapes.basic.TextBlock({
                            position : {
                                x : 800,
                                y : 500
                            },
                            id:v.vertexId,
                            size : {
                                width : 150,
                                height  : 60
                            },
                            attrs : {
                                "vertexType" : v.vertexType,
                                'rect': {
                                    fill: tableBgArr[colorNum],
                                    stroke:tableBgArr[colorNum],
                                    'follow-scale':true,
                                },
                                'isRightOpen' : isOpen.isRightOpen,
                                'isLeftOpen' : isOpen.isLeftOpen,
                                'div' : {
                                }
                            }
                        });
                        if(v.vertexType === 'dataobj'){
                            tableObj.attributes.attrs.div.html = '<p title="'+v.objectChname +'" class="TextBlockInfo">'+v.objectChname +'</p><p class="TextBlockInfo" title="'+v.dsName+'">《'+v.dsName+'》</p>';
                        }else {
                            tableObj.attributes.attrs.div.html = '<p title="'+v.objectChname +'" class="TextBlockInfo"><i style="margin-right: 5px;" class=" iconfont icon-SQL"></i>'+v.objectChname +'</p><p class="TextBlockInfo" title="'+v.dsName+'">《'+v.dsName+'》</p>';

                        }

                        tableObjArr.push(tableObj);
                    }else {
                        var objImg = new joint.shapes.basic.Image({
                         //   "position":{"x":911.2059561821235,"y":665.8860407683019},
                            "size":{"width":40,"height":40},
                            "angle":0,
                            "id":v.vertexId,
                            "description":"image",
                            "z":1,
                            "attrs":{
                                "text":{"text":v.dxflowName?v.dxflowName:'',"ref-y":5},
                                "image":{
                                    "width":40,"height":40,
                                    "class":"TU",
                                    "vertexType" : v.vertexType,
                                    "href":"./img/TU.png",
                                    'text' : v.dxflowName?v.dxflowName:''
                                }
                            }
                        });
                        tableObjArr.push(objImg);
                    }

                });

                if(result.object.lines.length > 0){
                    console.log(result.object.lines);
                    $.each(linkArr,function (i, v) {
                        var linkArr = new joint.shapes.app.Link({
                            "source":{"id":v.from},
                            "target":{"id":v.to},
                            //  "router":{"name":"manhattan"},
                            //  "connector":{"name":"rounded"},
                            smooth: true,
                            "id":v.lineId,
                            "attrs":{
                                ".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},
                                ".marker-target":{"fill":"#20C1DD","stroke":"#20C1DD","d":"M 10 0 L 0 5 L 10 10 z"},
                                "rowsizeInc" : v.rowsizeInc ? v.rowsizeInc : "",
                                "rowsizeTotal" : v.rowsizeTotal?v.rowsizeTotal:'',
                                'isdata' : v.isdata,
                            }
                            ,
                            "labels": [
                                {"position": 0.5, "attrs": {"text": {"text": v.rowsizeInc ? v.rowsizeInc :""}}}
                            ],
                            '.tool-remove' : null
                        });

                        tableObjArr.push(linkArr)
                    });
                }
                //添加元素
                graph.addCell(tableObjArr);

                //移除元素
                $('.tool-remove').remove();
                $('.tool-options').remove();
                //页面元素布局
                joint.layout.DirectedGraph.layout(graph, {
                    setLinkVertices: false,
                    marginX: 800,
                    marginY: 500,
                    rankSep : 150,
                    rankDir: "LR",
                    ranker : '500px'
                });
                //回调函数
                cb && cb();

                //开启数据量监控
            //   console.log($(".dataMonitor",parent.document).prop('checked'));
               if($(".dataMonitor",parent.document).prop('checked')) {
                   var day = $(".events .selected",parent.document).attr('data-date');
                   requestRowsize(day);
               }

            },
            error : function (result) {
                layer.msg('加载失败')
            }
        });
}

//请求增量全量封装
function requestRowsize(day,changeTime) {

    var isdataArr =  graph.getLinks().filter(function (v, i, arr) {  //筛选有isdata的线数组
        return v.attributes.attrs.isdata
    });
    var condList = [];
    $.each(isdataArr,function (i, v) {                                 //有isdata的线数组替换成请求数据量时的数组
        condList.push({'from':v.attributes.source.id,'to':v.attributes.target.id})
    });

    if(condList.length > 0 ){           //如果有数据量
        console.log(day);
        $.ajax({
            url :requestUrl+'/rest/dataRelation/findDxCount',
            type : 'POST',
            dataType : 'JSON',
            data :{'day':day,'condList':JSON.stringify(condList)},
            success : function (result) {
                console.log(result);
                if(result.msgCode === 0 && result.object.lines.length>0){
                    $.each(result.object.lines,function (i, v) {
                        var topV = v;
                        $.each(isdataArr,function (i, v) {
                            if(topV.from === v.attributes.source.id && topV.to === v.attributes.target.id){ //判断是该条线
                                console.log(v);
                                //线上数据保存到属性里
                                v.attributes.attrs.rowsizeInc = parseInt(topV.rowsizeInc);
                                v.attributes.attrs.rowsizeTotal = parseInt(topV.rowsize);


                                //线上数据更新
                                if($(".toggle_on .bootstrap-switch-on", parent.document).length > 0){
                                    updateLink(v,parseInt(topV.rowsizeInc));
                                }else {
                                    updateLink(v,parseInt(topV.rowsize));
                                }

                            }
                        })
                    });
                    if(changeTime === 0){
                        layer.msg('数据量加载完成',{time:1000})
                    }else if(changeTime === 1){
                        layer.msg('刷新完成',{time:1000})
                    }

                }else {
                    console.log('没有数据量');
                    $.each(isdataArr,function (i, v) {
                        updateLink(v,null)
                    });
                    if(changeTime === 0){
                        layer.msg('数据量为空',{time:1000})
                    }
                }
            }
        })
    }

}

//当前元素的所有源溯或者影响展开
function showTable(currentElement,obj,direction) {
    var list = [];  //元素id数组
    list.push(currentElement.id); //排除当前元素
    findRelateModel(currentElement);
    console.log(list);
    function findRelateModel(currentElement){     //子元素相关的所有元素
        var NeighborsBPMNArr = graph.getNeighbors(currentElement,obj);  //相邻元素数组
            $.each(NeighborsBPMNArr,function(i,v){        //遍历相关元素
                if(list.indexOf(v.id) === -1){
                    list.push(v.id);
                    console.log(list);
                    if(direction === 'left'){
                        v.attributes.attrs.isLeftOpen = true;
                    }else {
                        v.attributes.attrs.isRightOpen = true;
                    }
                    findRelateModel(v);               //回调
                }
            })


    }
}

//两个数组不同的部分
function array_diff(a, b) {
    for(var i=0;i<b.length;i++)
    {
        for(var j=0;j<a.length;j++)
        {
            if(a[j]==b[i]){
                a.splice(j,1);
                j=j-1;
            }
        }
    }
    return a;
}

function updateLink(v,num) {
    v.attributes.labels[0].attrs.text.text =  num;
    var options = {
        cell:v,
        inputs: {
            labels: {
                type: 'list',
                group: 'labels',
                label: 'Labels',
                attrs: {
                    label: {
                        'data-tooltip': 'Set (possibly multiple) labels for the link',
                        'data-tooltip-position': 'right',
                        'data-tooltip-position-selector': '.joint-inspector'
                    }
                },
                item: {
                    type: 'object',
                    properties: {
                        attrs: {
                            text: {
                                text: {
                                    type: 'content-editable',
                                    label: 'text',
                                    defaultValue: 'label',
                                    index: 1,
                                    attrs: {
                                        label: {
                                            'data-tooltip': 'Set text of the label',
                                            'data-tooltip-position': 'right',
                                            'data-tooltip-position-selector': '.joint-inspector'
                                        }
                                    }
                                },
                            },
                        }
                    }
                }
            }
        },
        live : false,
        getFieldValue : function (attribute, type) {
          if(type === 'content-editable'){
              $(attribute).text(num);
          }
        }
    };
    var inspector = new joint.ui.Inspector(options).render();

  //  inspector.$el.appendTo($('body'));
    inspector.updateCell();
    inspector.remove();
}

